package com.example.smartwaterapi.security;

import com.example.smartwaterapi.entity.User;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * Spring Security用户实体类
 */
public class SecurityUser implements UserDetails {

    @Getter
    private final User user;
    private final Collection<SimpleGrantedAuthority> authorities;

    public SecurityUser(User user) {
        this.user = user;
        // 默认授予ROLE_USER角色
        this.authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
    }

    /**
     * 获取用户ID
     */
    public Long getUserId() {
        if (user == null) {
            System.err.println("严重错误: SecurityUser中的user对象为null");
            return null;
        }
        
        Long userId = user.getId();
        if (userId == null) {
            // 如果ID为null，记录详细信息以便排查
            String openid = user.getOpenid();
            String nickname = user.getNickname();
            String uuid = user.getUuid();
            
            System.err.println("严重错误: 用户ID为null - openid=" + openid + 
                              ", nickname=" + nickname +
                              ", uuid=" + uuid);
        }
        return userId;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        // 从数据库存储的加密密码或其他密码字段
        return user.getUnlockPassword();
    }

    @Override
    public String getUsername() {
        // 使用手机号作为用户名，如果为空则使用openid
        return (user.getPhone() != null && !user.getPhone().isEmpty()) ? user.getPhone() : user.getOpenid();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStatus() == 1;
    }
} 